package com.beone.admin.security.handler;

import com.base.common.RequestContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @title
 * @Author 覃球球
 * @Version 1.0 on 2017/12/21.
 * @Copyright 长笛龙吟
 */
public class RequestTypeAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    private Logger logger = LoggerFactory.getLogger(RequestTypeAuthenticationEntryPoint.class);
    /**
     * @param loginFormUrl URL where the login page can be found. Should either be
     *                     relative to the web-app context path (include a leading {@code /}) or an absolute
     *                     URL.
     */
    public RequestTypeAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    /**
     * Performs the redirect (or forward) to the login form URL.
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response
            , AuthenticationException authException) throws IOException, ServletException {
        if(RequestContextUtils.isAjaxRequest(request)){
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authentication by ajax!");
            return;
        }

        if(super.isUseForward()){
            super.commence(request, response, authException);
            return;
        }

        invokeTimeout(request, response);
    }

    public void invokeTimeout(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException{
        logger.info("login timeout, redirect url ");
        /** redirect url 请求会话超时*/
        response.setContentType("text/html;charset=UTF-8");
        java.io.PrintWriter out = response.getWriter();
        out.write("<script type='text/javascript'>");
        out.write("var win = window.parent || window;");
        out.write("win.location.href = '" + request.getContextPath() + "/login';");
        out.write("</script>");
        out.close();
    }
}
